//
//  CityListView.m
//  CityListDemo
//
//  Created by Apple on 2018/3/24.
//  Copyright © 2018年 techbird. All rights reserved.
//

#import "CityListView.h"
@interface CityListView()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)NSDictionary *cityListData;
@property(nonatomic,strong)NSArray *keys;
@end

static NSString *cellid = @"cellid";
@implementation CityListView

- (void)awakeFromNib{
    [super awakeFromNib];
    [self setupUI];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    UITableView *tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    tableView.dataSource = self;
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellid];
    [self addSubview:tableView];
    _cityListData = [self loadCityListData];
    _keys = _cityListData.allKeys;
    
    //    _keys = [_keys sortedArrayUsingSelector:@selector(compare:)];
    _keys = [_keys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        //等同于sortedArrayUsingSelector方法，升序
        return [obj1 compare:obj2];
        //降序
        //        return [obj2 compare:obj1];
        //随机，因为随机3返回的只会是是（0，1，2），而排序实际上用到的值是（-1，0，1）
        //        return arc4random_uniform(3-1);
    }];
    
}

#pragma mark - <UITableViewDataSource,UITableViewDelegate>
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _keys.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *key = _keys[section];
    return  ((NSArray *) _cityListData[key]).count;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return _keys[section];
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return _keys;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid forIndexPath:indexPath];
    NSString *key = _keys[indexPath.section];
    cell.textLabel.text = _cityListData[key][indexPath.row];
    return cell;
}

/**
 加载数据
 
 @return 城市数据字典
 */
-(NSDictionary *)loadCityListData{
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"cityList.plist" withExtension:nil]];
    return dict.copy;
}
@end
